from service import Service
from model.sprint import SprintDao
from lib.validator import Validator
from lib.form import Form
from bson.objectid import ObjectId
import time

class SprintService(Service):
    def __init__(self):
        self.dao = SprintDao()
    
    def get_sprint(self, sid):
        """
        Argument:
            sid -- string type
        """
        if sid != '':
            oid = ObjectId(sid)
            sprint = self.dao.find_one({'_id':oid})
            return self.get_dict(sprint)
        else:
            return None
        
    def delete_sprint(self, sid):
        if sid != '':
            oid = ObjectId(sid)
            self.dao.remove({'_id':oid})
    
    def get_sprints(self, query={}):
        """ Get the sprints for rendering the html
        """
        sprints = self.dao.find(query)
        
        if sprints is not None:
            _sprints = []
            for sprint in sprints:
                _sprints.append(self.get_dict(sprint))
            return _sprints
        else:
            return []

    def get_project_oid(self, sprint_id):
        _sprint = self.dao.find_one({'_id':ObjectId(sprint_id)})
        if _sprint is None:
            return None
        else:
            return _sprint['project_id']
      
    def submit_sprint(self, _dict, mode):
        """
        Return:
        The '_id' value of to_save or [None] if manipulate is False and to_save has no _id field.
        """
        _input = self.get_dao_input(_dict, mode)
        
        # following are hidden fields
        if mode == 'edit':
            _input['created'] = _dict['created']
        else:
            _input['created'] = time.time()
        return self.dao.save(_input)


class SprintValidator(Validator):
    def __init__(self):
        Validator.__init__(self)
              
        self.rules = {'name': { 
                                'required' : [None, True],
                                'minlength':[None, 1],
                                'maxlength':[None, 256]
                                },
                      'description': { 
                                'maxlength':[None, 256]
                                }
        }

    
class SprintForm(Form):
    """ Submit user form
    """
    def __init__(self):
        """Only accept POST request
        """
        Form.__init__(self)
        self.validator = SprintValidator()
        
        if self.is_submitted():
            self.errors = self.validator.validate(self.input)

        
    def has_error(self):
        return self.errors != []

